package cg;

import java.text.DecimalFormat;

public class CumulatedGain {
	
	private int baseOfLog = 2; //the base of logarithm used to calculate DCG, initialized as 2.
	
	/**
	 * set the base of logarithm
	 * @param base
	 */
	public void setBaseOfLog(int base){
		baseOfLog = base;
	}
	
	/**
	 * @param gain
	 * @param idealGain
	 * @return the average of normalized-vector(DCG, iDCG)
	 */
	public double measure(int[] gain, int[] idealGain){
		int length = gain.length;
		//calculate cumulated gain(cg) & ideal cumulated gain(icg)
		int[] cg = new int[length]; 
		int[] icg = new int[length];
		for(int i=0; i<length; i++){
			if(i == 0){
				cg[i] = gain[i];
				icg[i] = idealGain[i];
			}else{
				cg[i] = cg[i-1] + gain[i];
				icg[i] = icg[i-1] + idealGain[i];
			}
			//System.out.print(cg[i]+" ");
			//System.out.print(icg[i]+" ");
			
		}
		//calculate discounted cumulated gain(dcg) & ideal discounted cumulated gain(idcg)
		double[] dcg = new double[length]; 
		double[] idcg = new double[length];
		for(int i=0; i< length; i++){
			if(i < baseOfLog -1){
				dcg[i] = cg[i];
				idcg[i] = icg[i];
			}else{
				dcg[i] = dcg[i-1] +gain[i]/(Math.log(i+1)/Math.log(baseOfLog));
				idcg[i] = idcg[i-1] +idealGain[i]/(Math.log(i+1)/Math.log(baseOfLog));
			}
//			System.out.print(dcg[i]+" ");
//			System.out.print(idcg[i]+" ");
		}

		double[] ncg = new double[length];
		double[] ndcg = new double[length];
		double sumCg = 0, sumDcg = 0;
		for(int i=0; i<length; i++){
			ncg[i] = (double)cg[i]/(double)icg[i];
			ndcg[i] = dcg[i]/idcg[i];
			sumCg += ncg[i];
			sumDcg += ndcg[i];
			//System.out.print(ncg[i]+" ");
			
			//System.out.print(ndcg[i]+" ");
		}
		
		double result = sumDcg/length;
		
		return result;
	}

	public void test(){
		int[] testCase = {3, 2, 3, 0, 0, 1, 2, 2, 3, 0};
		int[] idealCase = {3, 3, 3, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0};
		
		System.out.print(measure(testCase, idealCase));
	
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		CumulatedGain cg = new CumulatedGain();
		cg.test();
	}

}
